package com.example.blog_spring.service;

import com.example.blog_spring.constant.Constants;
import com.example.blog_spring.mapper.UserMapper;
import com.example.blog_spring.model.Result;
import com.example.blog_spring.model.UserInfo;
import com.example.blog_spring.utils.JwtUtils;
import com.example.blog_spring.utils.SecurityUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Result<String> login(String userName, String password, HttpSession session) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("账号或密码不能为空");
        }
        UserInfo userInfo = userMapper.selectByName(userName);
        if(userInfo == null){
            return Result.fail("用户不存在");
        }
        if(!SecurityUtils.verity(password, userInfo.getPassword())){
            return Result.fail("密码错误");
        }
        log.info("登录成功......  用户名: " + userName);
        session.setAttribute("userId", userInfo.getId());
        Map<String, Object> secret = new HashMap<>();
        secret.put(Constants.TOKEN_ID, userInfo.getId());
        secret.put(Constants.TOKEN_USERNAME, userInfo.getUserName());
        String token = JwtUtils.generateToken(secret);
        return Result.success(token);
    }

    public UserInfo selectById(Integer userId){
        return userMapper.selectById(userId);
    }

    public Result<String> register(String userName, String password, String confirmPassword, String githubAddress) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)
                || !StringUtils.hasLength(confirmPassword)){
            return Result.fail("账号或密码不能为空");
        }
        if(!password.equals(confirmPassword)){
            return Result.fail("两次输入的密码不一致");
        }
        UserInfo userInfo = userMapper.selectByName(userName);
        if(userInfo != null){
            return Result.fail("该用户已注册");
        }
        String encrypt = SecurityUtils.encrypt(password);
        Integer result = userMapper.addUserInfo(userName, encrypt, githubAddress);
        if(result == 1) {
            log.info("用户 " + userName + " 注册成功");
            return Result.success("注册成功");
        } else {
            return Result.fail("注册失败");
        }
    }

    public Integer updateUserInfo(UserInfo userInfo) {
        return userMapper.updateUserInfo(userInfo);
    }
}
